<template>
  <div>
    <el-dialog
      width="1024px"
      :close-on-click-modal="false"
      :show-close="true"
      v-bind="$attrs"
      v-on="$listeners"
      @open="onOpen"
      @close="onClose"
    >
      <div slot="title">
        {{ formData.id != null ? '修改商机' : '新增商机' }}
      </div>
      <div class="sketch_content">
        <el-form label-position="top" ref="elForm" :model="formData" :rules="rules" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商机名称" prop="businessName">
                <el-input v-model="formData.businessName" style="width: 100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerName">
                <el-input @click.native="customerNameClick" v-model="formData.customerName" style="width: 100%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="下次联系时间" prop="nextTime">
                <el-date-picker value-format="yyyy-MM-dd hh:mm:ss" v-model="formData.nextTime" type="datetime"
                                placeholder="请选择" style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计成交日期" prop="dealDate">
                <el-date-picker value-format="yyyy-MM-dd hh:mm:ss" v-model="formData.dealDate" type="datetime"
                                placeholder="请选择" style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商机状态组" prop="typeId">
                <el-select v-model="formData.typeId" style="width: 100%" placeholder="请选择">
                  <el-option
                    v-for="type in businessTypeList"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售阶段" prop="statusId">
                <el-select v-model="formData.statusId" style="width: 100%" placeholder="请选择">
                  <el-option
                    v-for="type in businessStatusList"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商机金额" prop="money">
                <el-input v-model="formData.money" :disabled="true" prefix-icon="el-icon-mobile-phone"
                          style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5}"
                  placeholder="请输入内容"
                  v-model="formData.remark"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <dialog-add-product ref="dialogAddProduct" @callback="productSelectCallback"></dialog-add-product>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer" style="height: 25px">
        <el-button size="small" type="primary" @click="submitForm" :loading="submitLoading">保 存</el-button>
        <el-button size="small" @click="onClose">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 客户选择对话框 -->
    <customer-select-popover ref="customerSelectPopover" @callback="customerDataCallback"/>
  </div>
</template>

<script>
import {
  getStatusByTypeId,
  listProductFromBusiness,
  saveHasKey,
  selectByPrimaryKey,
  selectType,
  updateByPrimaryKeySelective
} from '@/api/crm/Business'

import CustomerSelectPopover from '@/components/Crm/Customer/CustomerSelectPopover'
import DialogAddProduct from '@/components/Crm/Product/DialogAddProduct'

export default {
  inheritAttrs: false,
  name: 'businessDialog',
  dicts: ['sys_crm_product_category', 'sys_crm_product_unit'],
  components: {
    CustomerSelectPopover,
    DialogAddProduct
  },
  props: {
    pk: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      title: '添加商机', // 对话框标题
      dialogVisible: false, // 对话框懒加载
      submitLoading: false, // 提交加载动画
      formData: {
        id: null, // 主键id
        businessName: '', // 商机名称
        customerId: null, // 客户id
        customerName: '', // 客户名称
        money: 0, // 商机金额
        dealDate: null, // 预计成交日期
        typeId: null, // 商机状态组
        statusId: null, // 销售阶段
        typeName: '', // 商机状态组名
        nextTime: null, // 下次联系时间
        remark: '', // 备注
        discountRate: 0, // 整单折扣
        productList: [] // 产品集合
      },
      totalMoney: 0, // 总金额
      // 规则
      rules: {
        customerName: [{ required: true, message: '客户名称不能为空', trigger: 'change' }],
        typeId: [{ required: true, message: '请选择商机状态组', trigger: 'blur' }],
        businessName: [{ required: true, message: '商机名称不能为空', trigger: 'blur' }]
      },
      businessTypeList: [], // 商机状态列表
      businessStatusList: [], // 销售阶段列表
      queryParams: {
        page: 1,
        limit: 15,
        search: '',
        searchId: null
      }
    }
  },
  // 在实例创建完成后被立即调用
  created() {
    this.submitLoading = false
  },
  // 实例被挂在后调用
  mounted() {

  },
  // 监听值是否变化
  watch: {
    'formData.typeId': {
      deep: true,
      handler(n, o) {
        if (this.formData.typeId != null) {
          this.getStatusByTypeId(this.formData.typeId)
        }
      }
    }
  },
  // 方法
  methods: {
    // 对话框打开
    onOpen() {
      // 查询所有商机状态组
      selectType({ page: 1, limit: 10, data: {} }).then(res => {
        this.businessTypeList = res.data.records
      })
      if (this.pk != null) {
        this.queryParams.searchId = this.pk
        listProductFromBusiness(this.queryParams).then(res => {
          this.formData.productList = res.data.records
          this.$refs.dialogAddProduct.initProductData(this.formData)
        })
        selectByPrimaryKey(this.pk).then(res => {
          this.formData = res.data
        })
      }
    },
    // 对话框关闭
    onClose() {
      this.submitLoading = false
      this.$refs['elForm'].resetFields()
      this.$emit('update:visible', false)
    },
    // 提交
    submitForm() {
      this.submitLoading = true
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (this.formData.id != undefined) {
            // 修改
            updateByPrimaryKeySelective(this.formData).then(res => {
              this.$emit('list')
              this.dialogVisible = false
              this.submitLoading = false
            })
          } else {
            // 新增
            saveHasKey(this.formData).then(res => {
              this.$emit('list')
              this.dialogVisible = false
              this.submitLoading = false
            })
          }
        }
      })
    },
    // 获取当前商机状态组下的商机状态
    getStatusByTypeId(typeId) {
      getStatusByTypeId({ page: 1, limit: 10, typeId: typeId }).then(res => {
        this.businessStatusList = res.data
      })
    },
    // 客户名称点击事件
    customerNameClick() {
      this.$refs.customerSelectPopover.open()
    },
    // 客户选择完毕回调事件
    customerDataCallback(data) {
      this.formData.customerId = data.id
      this.formData.customerName = data.customerName
    },
    // 产品列表信息变化回调
    productSelectCallback({ discountRate, money, productList }) {
      this.formData.discountRate = discountRate
      this.formData.money = money
      this.formData.productList = productList
    }
  }
}
</script>

<style scoped>

</style>
